<?php 
/**
 * @version : 1.0
 * @package : lib/system
 * @name :  CTranslation
 * @todo:  Lớp  cơ sở CTranslation.  Dùng để phân tích xâu thành các từ khóa (TOKEN)
*/
class CTranslation
{
	public $code;
	public $tags;
	public $tokens;
	
	function __construct($code, $tags)
	{
		$this->code = $code;
		$this->tags = $tags;
	}
	function tokenize()
	{
		$pos = 0;
		$this->tokens = array();
		$expression = '/(';
		foreach($this->tags as $tag=>$expr)
		{
			if($expression != '/(')
			{
				$expression .= '|';
			}
			$expression .= $expr;
		}
		$expression .= ')/';
		$pos = 0;
		if(preg_match_all($expression, $this->code, $patterns, PREG_SET_ORDER|PREG_OFFSET_CAPTURE))
		{
			foreach($patterns as $pattern)
			{
				if($pos != $pattern[0][1])
				{
					$this->tokens[] = array('TEXT',array(substr($this->code,$pos,$pattern[0][1] - $pos)));
				}
				$pos = $pattern[0][1] + strlen($pattern[0][0]);
				foreach($this->tags as $tag=>$expr)
				{
					if(preg_match('/'.$expr.'/', $pattern[0][0]))
					{
						break;
					}
				}
				$shift = 2;
				foreach($pattern as &$param)
				{
					$shift += (intval($param[1]) == -1)?1:0;
					$param = $param[0];
				}
				$params = array();
				for($i = $shift; $i<sizeof($pattern);$i++)
				{
					$params[] = $pattern[$i];
				}
				$this->tokens[] = array($tag,$params);
			}
		}
		if($pos < strlen($this->code))
		{
			$this->tokens[] = array('TEXT',array(substr($this->code, $pos)));
		}
		return $this->tokens;
	}
}
function CTranslation($code, $tags)
{
	return new CTranslation($code, $tags);
}
?>